package com.blb.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码工具类
 */
public class CodeUtils {
    private static final int WIDTH=110;
    private static final int HEIGHT=42;
    private static final int NUM=4;
    private static final String STR="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";

    public static String createCode() throws IOException {
        String code="";
        Random random = new Random();
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
        Graphics gc = image.getGraphics();
        gc.setColor(Color.BLACK);
        gc.fillRect(0,0,WIDTH,HEIGHT);
        gc.setFont(new Font("微软雅黑",Font.BOLD,25));
        gc.setColor(Color.BLACK);
        gc.drawRect(0,0,WIDTH-1,HEIGHT-1);
        for (int i = 0; i < NUM; i++) {
            int index = random.nextInt(STR.length());
            char c = STR.charAt(index);
            code+=c;
            Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
            gc.setColor(color);
            gc.drawString(c+"",20*(i+1),30);
        }
        for (int i = 0; i < NUM; i++) {
            Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
            gc.setColor(color);
            gc.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));
        }
        ImageIO.write(image,"jpg",new FileOutputStream("D:/upload/eshop/"+"code.jpg"));
        return code;
    }
}
